package dhee.wtqshopproject.config;

import dhee.wtqshopproject.entity.User;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Aspect
@Component
public class SecurityAuditAspect {

    // 登录审计
    @Pointcut("execution(* dhee.wtqshopproject.service.UserService.login(..))")
    public void loginPointcut() {}

    // 关键操作审计
    @Pointcut("execution(* dhee.wtqshopproject.controller.UserController.upgradeToVip(..)) || " +
            "execution(* dhee.wtqshopproject.controller.UserController.downgradeFromVip(..)) || " +
            "execution(* dhee.wtqshopproject.controller.UserController.deleteUser(..))")
    public void criticalOperationPointcut() {}

    @AfterReturning(pointcut = "loginPointcut()", returning = "result")
    public void afterLogin(JoinPoint joinPoint, Object result) {
        if (result != null) {
            HttpServletRequest request =
                    ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

            String username = request.getParameter("username");
            String ip = request.getRemoteAddr();

            System.out.println("[SECURITY AUDIT] 登录成功 - 用户名: " + username
                    + ", IP: " + ip + ", 时间: " + LocalDateTime.now());
        }
    }

    @AfterReturning(pointcut = "criticalOperationPointcut()")
    public void afterCriticalOperation(JoinPoint joinPoint) {
        HttpServletRequest request =
                ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

        User currentUser = (User) request.getSession().getAttribute("currentUser");
        String operation = joinPoint.getSignature().getName();
        String ip = request.getRemoteAddr();

        System.out.println("[SECURITY AUDIT] 关键操作 - 用户: " + currentUser.getUsername()
                + ", 操作: " + operation + ", IP: " + ip + ", 时间: " + LocalDateTime.now());
    }
}